package cn.cumulomq.db;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import cn.cumulomq.service.AftnChannelService;
import cn.cumulomq.utils.FileUtil;
import cn.cumulomq.utils.PropertiesUtil;

public class ConfigDB {
	private static Logger logger = Logger.getLogger(AftnChannelService.class);
	private static SqlSessionFactory sqlSessionFactory;
	
	/**
	 * 创建SqlSessionFactory, 只创建一次不重创建
	 * @return SqlSessionFactory
	 */
	public static SqlSessionFactory getSessionFactory(){
		if(sqlSessionFactory==null){
			checkAndCreateDB();			
			String resource = "db-config.xml";
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream(resource);
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				logger.error(e);
			}
		}
		return sqlSessionFactory;
	}
	private static void checkAndCreateDB(){
		String configdbPath = PropertiesUtil.getProperty("configdb.url");
		File configdbFile = new File(configdbPath);
		if(!configdbFile.exists()){
			logger.info("Create new config database at : "+configdbFile.getAbsolutePath());
			configdbFile.getParentFile().mkdirs();
			InputStream inputStream = null;
			try {
				inputStream = Resources.getResourceAsStream("config.db");
				FileUtil.inputStreamToFile(inputStream, configdbFile);
			} catch (IOException e) {
				logger.error("Create config database error.",e);
			}
		}
		
	
				
	}

}
